import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:扫描指定⽬录，并找到名称中包含指定字符的所有普通⽂件（不包含⽬录），并且后续询问⽤⼾是否
 * 要删除该⽂件
 * User: wangxin
 * Date: 2024-08-15
 * Time: 15:40
 */
public class test1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入要扫描的根目录");
        String rootDirPath = scanner.next();
        File rootDir = new File(rootDirPath);
        if (!rootDir.isDirectory()) {
            System.out.println("你输入的根目录不存在或者不是目录！退出！");
            return;
        }
        System.out.print("请输入要找文件中的字符：");
        String token = scanner.next();
        ArrayList<File> result = new ArrayList<>();
        scanDir(rootDir, token, result);
        System.out.println(" 共找到了符合条件的⽂件 " + result.size() + "个");
        for (File f:result) {
            System.out.println(f.getAbsoluteFile() + "你是否删除，'是'输入'y',‘否’输入‘n'");
            String c = scanner.next();
            if(c.toLowerCase().equals("y")){
                f.delete();
            }
        }
    }

    private static void scanDir(File rootDir, String token, ArrayList<File> result) {
        File[] files = rootDir.listFiles();
        if(files == null||files.length == 0){
            return;
        }
        for (File f:files) {
          if(f.isDirectory()){
              scanDir(f,token,result);
          }else{
              if(f.getName().contains(token)){
                  result.add(f.getAbsoluteFile());
              }
          }
        }
    }
}